﻿using Nest;
using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Search.ElasticSearch.Cfg;
using System.IO;

namespace NHibernate.Search.ElasticSearch.Event
{
    public class FullTextIndexEventListener : IPostDeleteEventListener, IPostInsertEventListener,
                                              IPostUpdateEventListener,
                                              IInitializable,
                                              IDestructible
    {
        private NHibernateSearchConfiguration nHibernateSearchConfiguration;

        public virtual void Initialize(Configuration cfg)
        {
            this.nHibernateSearchConfiguration = NHibernateSearchConfiguration.Initialize(cfg);
        }
        public void OnPostInsert(PostInsertEvent @event)
        {

            if (nHibernateSearchConfiguration.IndexClassExists(@event.Persister.EntityName))
            {
                //var indexClass = nHibernateSearchConfiguration.GetIndexClass(@event.Persister.EntityName);
         
                //IndexRequest<object> request = new IndexRequest<object>(@event.Entity)
                //{
                //    Index = indexClass.Index,
                //    Type = indexClass.Type,
                //    Id = @event.Id.ToString()
                //};
                //nHibernateSearchConfiguration.GetElasticClient().Index<object>(request);
            }
        }
        public virtual void OnPostUpdate(PostUpdateEvent @event)
        {
            if (nHibernateSearchConfiguration.IndexClassExists(@event.Persister.EntityName))
            {
                //var indexClass = nHibernateSearchConfiguration.GetIndexClass(@event.Persister.EntityName);
                //UpdateRequest<object> request = new UpdateRequest<object>(@event.Entity)
                //{
                //    Index = indexClass.Index,
                //    Type = indexClass.Type,
                //    Id = @event.Id.ToString()
                //};
                //nHibernateSearchConfiguration.GetElasticClient().Update<object>(request);
            }

        }
        public virtual void OnPostDelete(PostDeleteEvent @event)
        {
            if (nHibernateSearchConfiguration.IndexClassExists(@event.Persister.EntityName))
            {
                //var indexClass = nHibernateSearchConfiguration.GetIndexClass(@event.Persister.EntityName);
                //int lenth = @event.Persister.EntityName.Split('.').Length;

                //DeleteRequest request = new DeleteRequest(new IndexNameMarker() { Name = indexClass.Index },
                //    new TypeNameMarker() { Name = indexClass.Type.Name, }, @event.Id.ToString());
                //nHibernateSearchConfiguration.GetElasticClient().Delete(request);
            }
        }

        public virtual void Cleanup() { }
    }
}
